package com.mengchengnet.chaperonage.ui.activity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.mengchengnet.chaperonage.BaseActivity;
import com.mengchengnet.chaperonage.R;
import com.mengchengnet.chaperonage.util.CountDownTimerUtils;
import com.mengchengnet.chaperonage.util.PreferenceUtil;
import com.mengchengnet.chaperonage.util.Url;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import static com.mengchengnet.chaperonage.ui.activity.RegisteredActivity.isPhoneNumberValid;

/**
 * Created by Administrator on 2017/8/16.
 */

public class NurseRegisterActivity extends BaseActivity implements View.OnClickListener{

    private EditText ed_number;//输入的手机号
    private EditText ed_code;//验证码
    private EditText ed_pass;//密码
    private TextView getCode;//获取验证码
    private Button btn_register;//注册
    private CountDownTimerUtils mCountDownTimerUtils;
    private RequestQueue requestQueue;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register_nurse);
        initView();
    }

    private void initView() {
        toolbarState = TOOLBAR_STYLE_BACK_TITLE;
        initToolbar("陪护师注册");
        ed_number= (EditText) findViewById(R.id.register_et_card_no);
        ed_code=(EditText) findViewById(R.id.register_et_verify_code);
        ed_pass=(EditText) findViewById(R.id.register_et_card_pass);
        getCode= (TextView) findViewById(R.id.register_tv_get_verify_code);
        btn_register= (Button) findViewById(R.id.register_btn_register);
        getCode.setOnClickListener(this);
        btn_register.setOnClickListener(this);
        mCountDownTimerUtils = new CountDownTimerUtils(getCode, 60000, 1000);
        requestQueue= Volley.newRequestQueue(getApplication());
    }

    private void sendCode() {
        StringRequest request = new StringRequest(Request.Method.POST, Url.SendVerificationCode,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String result) {
                        Log.e("注册界面", "发送验证码接口返回值："+result );
                        JSONObject jsonObject;
                        try {
                            if(result != null && result.startsWith("\ufeff"))
                            {
                                result =  result.substring(1);
                            }
                            jsonObject = new JSONObject(result);
                            Log.e("注册界面", "ppppppppppppp"+jsonObject.getString("code") );
                            if (jsonObject.getString("code").equals("00")){
                                mCountDownTimerUtils.start();
                                Toast.makeText(NurseRegisterActivity.this, "验证码已发送！", Toast.LENGTH_SHORT).show();
                            }
                            else if(jsonObject.getString("code").equals("01")) {
                                mCountDownTimerUtils.cancel();
                                Toast.makeText(NurseRegisterActivity.this,"该手机号码已注册",Toast.LENGTH_SHORT).show();
                            }else{
                                Toast.makeText(NurseRegisterActivity.this, "验证码获取失败", Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError arg0) {
                Toast.makeText(NurseRegisterActivity.this, "网络异常，注册失败，请稍后重试！", Toast.LENGTH_SHORT).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("version", PreferenceUtil.getString(getApplication(),"versionCode"));
                Log.e("注册界面", "发送短信验证接口版本参数："+PreferenceUtil.getString(getApplication(),"versionCode") );
                map.put("phoneNumber", ed_number.getText().toString().trim());
                Log.e("注册界面", "发送短信验证接口手机号参数："+ed_number.getText().toString().trim() );
                map.put("type", "register");
                return map;
            }
        };
        request.setTag("GetFenZu");
        request.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, // 默认超时时间，应设置一个稍微大点儿的
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, // 默认最大尝试次数
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        requestQueue.add(request);

    }


    private void checkCode() {
        StringRequest request = new StringRequest(Request.Method.POST, Url.CheckCode,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String result) {
                        Log.e("注册界面", "校验验证码接口返回值："+result);
                        JSONObject jsonObject;
                        try {
                            if(result != null && result.startsWith("\ufeff"))
                            {
                                result =  result.substring(1);
                            }

                            jsonObject = new JSONObject(result);
                            if (jsonObject.getString("code").equals("00")){
                                register();
                                //Toast.makeText(NurseRegisterActivity.this, "验证码正确", Toast.LENGTH_SHORT).show();
                            }
                            else {
                                mCountDownTimerUtils.cancel();
                                Toast.makeText(NurseRegisterActivity.this,"输入的验证码错误",Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError arg0) {
                Toast.makeText(NurseRegisterActivity.this, "网络异常，注册失败，请稍后重试！", Toast.LENGTH_SHORT).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("phoneNumber", ed_number.getText().toString().trim());
                map.put("verificationCode", ed_code.getText().toString().trim());
                Log.e("注册界面", "校验短信验证接口手机号参数："+ed_number.getText().toString().trim() );
                Log.e("注册界面", "校验短信验证接口验证码参数："+ed_code.getText().toString().trim() );
                return map;
            }
        };
        request.setTag("GetFenZu");
        request.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, // 默认超时时间，应设置一个稍微大点儿的
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, // 默认最大尝试次数
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        requestQueue.add(request);

    }

    private void register() {
        StringRequest request = new StringRequest(Request.Method.POST, Url.Register,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String result) {
                        Log.e("注册界面", "注册接口返回值："+result);
                        JSONObject jsonObject;
                        try {
                            if(result != null && result.startsWith("\ufeff"))
                            {
                                result =  result.substring(1);
                            }

                            jsonObject = new JSONObject(result);
                            if (jsonObject.getString("code").equals("00")){
                                PreferenceUtil.putString(getApplicationContext(),"userId",jsonObject.getString("user_id"));
                                Toast.makeText(NurseRegisterActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
                                startActivityAndFinish(CheckActivity.class);
                            }
                            else {
                                Toast.makeText(NurseRegisterActivity.this,"注册失败",Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError arg0) {
                Toast.makeText(NurseRegisterActivity.this, "网络异常，注册失败，请稍后重试！", Toast.LENGTH_SHORT).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("version", PreferenceUtil.getString(getApplication(),"versionCode"));
                map.put("loginId", ed_number.getText().toString().trim());
                map.put("password", ed_pass.getText().toString().trim());
                Log.e("注册界面", "注册接口手机号参数："+ed_number.getText().toString().trim() );
                Log.e("注册界面", "注册接口密码参数："+ed_pass.getText().toString().trim() );
                Log.e("注册界面", "注册接口版本号参数："+PreferenceUtil.getString(getApplication(),"versionCode") );
                return map;
            }
        };
        request.setTag("GetFenZu");
        request.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, // 默认超时时间，应设置一个稍微大点儿的
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, // 默认最大尝试次数
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        requestQueue.add(request);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.register_tv_get_verify_code:
                if (isPhoneNumberValid(ed_number.getText().toString().trim())) {
                    sendCode();
                }
                else {
                    Toast.makeText(NurseRegisterActivity.this,"请输入正确的手机号码!",Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.register_btn_register:
                if(ed_code.getText().toString().isEmpty()){
                    Toast.makeText(NurseRegisterActivity.this,"验证码不能为空",Toast.LENGTH_LONG).show();
                }else if(ed_code.getText().toString().length()<6){
                    Toast.makeText(NurseRegisterActivity.this,"验证码格式错误",Toast.LENGTH_LONG).show();
                }else {
                    checkCode();
                }
               // startActivityAndFinish(CheckActivity.class);

                break;
        }
    }
}
